package com.gy.boot.common.util;

import cn.hutool.extra.servlet.ServletUtil;
import com.gy.boot.common.jwt.JWT;
import com.gy.boot.common.jwt.JWT;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

public class HttpContextUtil {

	public static String getS() {
		return getHttpServletRequest().getServletContext().getContextPath();
	}

	public static HttpServletRequest getHttpServletRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}

	public static String getDomain() {
		HttpServletRequest request = getHttpServletRequest();
		StringBuffer url = request.getRequestURL();
		return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
	}

	public static String getOrigin() {
		HttpServletRequest request = getHttpServletRequest();
		return request.getHeader("Origin");
	}

	/**
	 * 获取当前用户JWT过滤的userId
	 * */
	public static Long getJwtUserId() {
		try {
			return getJwtUserId(getHttpServletRequest());
		} catch (Exception e) {
			return null;
		}
	}

	public static Long getJwtUserId(HttpServletRequest request) {
		if (request == null) {
			return null;
		}
		Object userIdObj = request.getAttribute(JWT.USER_ID);
        if (userIdObj == null) {
            return null;
        }
        String userId = userIdObj.toString();
		if (BlankUtil.isBlank(userId)) {
			return null;
		}
		return Long.parseLong(userId);
	}

	/**
	 * 获取当前员工登录角色ID
	 * */
	public static Integer getJwtRoleId() {
		try {
			return getJwtRoleId(getHttpServletRequest());
		} catch (Exception e) {
			return null;
		}
	}

	public static Integer getJwtRoleId(HttpServletRequest request) {
		if (request == null) {
			return null;
		}
		Object userIdObj = request.getAttribute(JWT.ROLE_ID);
        if (userIdObj == null) {
            return null;
        }
        String userId = userIdObj.toString();
		if (BlankUtil.isBlank(userId)) {
			return null;
		}
		return Integer.parseInt(userId);
	}

	/**
	 * 获取 Request 参数
	 * */
	public static Map<String, String> getParams() {
		try {
			return ServletUtil.getParamMap(getHttpServletRequest());
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 获取 IP
	 * */
	public static String getIP() {

		return null;
	}


}
